package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.AnswerInfo;
import com.ycsj.goldmedalnewconcept.bean.TopicInfo;
import com.ycsj.goldmedalnewconcept.bean.TopicInfo.QuestionListBean;
import com.ycsj.goldmedalnewconcept.bean.timeresq;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.fragment.AnswerFragment;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;
import com.ycsj.goldmedalnewconcept.view.CanotSlidingViewpager;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@SuppressLint("NewApi")
public class FollowReadDetailsActivity extends FragmentActivity implements
		View.OnClickListener, OnPageChangeListener {

	// 外层的加载布局
	private LinearLayout llLoading;

	// 内容布局
	private LinearLayout llContent;

	// 进度条对象
	private ProgressBar pb;

	// 显示进度条的文字
	private TextView tvPb;

	// 返回
	private LinearLayout llBack;

	// ViewPager对象
	private CanotSlidingViewpager vp;

	// 获取传递过来的班级lESSON_ID和LESSON_NAME
	private String lessonId, lessonName;

	// 填充Vp的Framgent集合
	private List<Fragment> mFragments;

	// ViewPager的适配器
	private VpAdapter adapter;

	// 记录当前Vp的位置
	private int vpPos = 0;

	// 用户名
	private String account;

	// 用户角色
	private String role;
	
	// 用户角色
	private List<Integer> currentItemList;

	// 计时rid
	private String rid;
		
	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_follow_details);
		// 设置状态栏
		setBar();

		// 获取年级ID和名称
		initData();

		// 初始化View
		initView();

		// 注册广播
		registerBroadCast();

		// 设置监听
		InitListener();

		// 设置初始数据
		httpData();
	}

	
	
	
	/**
	 * 注册广播的方法
	 */
	private void registerBroadCast() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(AnswerFragment.NEXT_ACTION);
		registerReceiver(new NextReceiver(), filter);
		IntentFilter filter1 = new IntentFilter();
		
		filter1.addAction(AnswerListDetailsActivity.FINISH);
		registerReceiver(new FinishReceiver(), filter1);
		
		IntentFilter filter2 = new IntentFilter();
        filter2.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter2.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter2.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(new TimingReceiver(), filter2);
	}


	
	/**
	 * 断网计时广播接受者
	 * 
	 * @author Administrator
	 *
	 */
	class TimingReceiver extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			
			 // 监听网络连接，包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
	        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
	            //获取联网状态的NetworkInfo对象
	            NetworkInfo info = intent
	                    .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
	            if (info != null) {
	                //如果当前的网络连接成功并且网络连接可用
	                if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
	                    if (info.getType() == ConnectivityManager.TYPE_WIFI
	                            || info.getType() == ConnectivityManager.TYPE_MOBILE) {
	                    	
	                    	Log.i("test", "网络重新连接");
	        				
	        				String gradeid = String.valueOf(lessonId).substring(0, 4);
	        				HttpUtils httpUtils2 = new HttpUtils();
	        				httpUtils2.configCurrentHttpCacheExpiry(1000);
	        				httpUtils2.send(HttpMethod.GET,
	        						NetConstant.USERONLINE
	        								+ "InitInterfaceBegin.aspx?msg=1&type=9&account="
	        								+ SPUtils.getString(FollowReadDetailsActivity.this, "account")
	        								+ "&gradeid=" + gradeid + "&lessonid=" + lessonId,
	        						callBackTime);
	                    }
	                }
	            }
	        }
		}
	}
	
	/**
	 * 接受到AnswerFragment传递过来的Vp翻页的广播接受者
	 * 
	 * @author Administrator
	 *
	 */
	class NextReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 进行翻页处理
			vp.setCurrentItem(vpPos + 1);
		}
	}
	
	
	
	class FinishReceiver extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			finish();
		}
	}

	/**
	 * 获取年级ID和年级名称的方法
	 */
	private void initData() {
		lessonId = getIntent().getStringExtra("lESSON_ID");
		lessonName = getIntent().getStringExtra("LESSON_NAME");
		account = SPUtil.getString(FollowReadDetailsActivity.this,"account","");
		role = SPUtil.getString(FollowReadDetailsActivity.this,"role","");
		 Log.i("test", "lessonId的值是:" + lessonId + "lessonName的值是:" +
		 lessonName+"account="+account);
		
		 currentItemList = new ArrayList<Integer>();
		 
	}

	/**
	 * 初始化View的方法
	 */
	private void initView() {
		llBack = (LinearLayout) findViewById(R.id.ll_back);
		vp = (CanotSlidingViewpager) findViewById(R.id.vp);
		pb = (ProgressBar) findViewById(R.id.pb);
		tvPb = (TextView) findViewById(R.id.tv_pb);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		llContent = (LinearLayout) findViewById(R.id.ll_content);
		llContent.setVisibility(View.GONE);
		llLoading.setVisibility(View.VISIBLE);
		vp.setScrollble(false);
	}

	/**
	 * 设置监听的方法
	 */
	private void InitListener() {
		llBack.setOnClickListener(this);
		vp.setOnPageChangeListener(this);
	}

	/**
	 * 通过请求服务器获取模块数据的方法,暂时模拟数据
	 */
	private void httpData() {

		// 注意:当前请求是Get请求

		OkHttpClient mOkHttpClient = new OkHttpClient();

		String getUrl = NetConstant.HOST2+"Test_Bank/UnitTest/GetLessonRepeatQuestion.aspx?"
				+ "lessonid="+lessonId+"&account="+account+"&done=0&role="+role;

		Request request = new Request.Builder().url(getUrl).get().build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {

				// 请求失败
				// 没有数据
				runOnUiThread(new Runnable() {
					public void run() {
						if (null != llLoading) {
							llLoading.setVisibility(View.GONE);
						}
						UiHelper.toast(FollowReadDetailsActivity.this, "网络错误");
						return;
					}
				});
			}

			@SuppressWarnings("static-access")
			@Override
			public void onResponse(Response arg0) throws IOException {
				// 请求成功
				String json = arg0.body().string();
				
				Log.e("test", "json"+json);
				try {
					if (!TextUtils.isEmpty(json)) {
						TopicInfo info = GsonUtil.jsonToBean(json,
								TopicInfo.class);
						// 取出所有的题目信息
						List<QuestionListBean> question_list = info
								.getQuestion_list();
						if (question_list == null || question_list.size() == 0) {
							// 证明当前没有题目信息
							runOnUiThread(new Runnable() {
								public void run() {

									if (null != llLoading) {
										llLoading.setVisibility(View.GONE);
									}

									UiHelper.toast(
											FollowReadDetailsActivity.this,
											"该单元无数据");
									return;
								}
							});

						} else {
							// 证明有题目信息,创建所有的题目集合
							mFragments = new ArrayList<>();
							//保存所有题目信息的集合
							List<AnswerInfo> answerDatas= new ArrayList<>();
							for (int i = 0; i < question_list.size(); i++) {
								mFragments.add(AnswerFragment.newInstance(
										question_list.get(i), i,
										question_list.size(), lessonId));

								// 设置答题列表的默认值
								AnswerInfo answerInfo = new AnswerInfo();
//								answerInfo.setAudioPath("");
//								answerInfo.setPlay(false);
//								answerInfo.setRecord(false);
//								answerInfo.setQuestionContent(question_list
//										.get(i).getSpeechtest());
//								answerInfo.setScore(0);
//								answerInfo.setShowScore(true);
//								answerInfo.setPostion(i);
//								answerInfo.setLessionId(lessonId);

								answerInfo.audioPath = "";
								answerInfo.path = question_list.get(i).getAudio();
								
								answerInfo.isPlay = false;
								answerInfo.isRecord = false;
								answerInfo.questionContent = question_list.get(
										i).getDialogue();
								answerInfo.score = 0;
								answerInfo.isShowScore = true;
								answerInfo.postion = i;
								answerInfo.lessionId = lessonId;
								answerInfo.isAllowTouch = true;
								answerInfo.isEnabled = true;

								
								answerInfo.question_id = question_list.get(i)
										.getQuestion_id();
								answerInfo.question_type = question_list.get(i)
										.getQuestion_type();

//								// 保存答案信息
//								AnswerManager.getInstance().addAnswer(i,
//										answerInfo);
								// 保存答案信息
								answerDatas.add(answerInfo);
								
								//保存到Sp中 
								SPUtils.put(FollowReadDetailsActivity.this, lessonId, GsonUtil.listToJson(answerDatas));
							}

							// 更新页面
							runOnUiThread(new Runnable() {
								public void run() {
									if (null != llLoading) {
										llLoading.setVisibility(View.GONE);
									}

									if (null != llContent) {
										llContent.setVisibility(View.VISIBLE);
									}
									// 设置ViewPager的适配器
									initVp();
									// 设置显示显示进度和显示进度的文字
									pb.setProgress(parsePb(1, mFragments.size()));
									tvPb.setText("1/" + mFragments.size());
								}
							});

						}
					} else {
						// 没有数据
						runOnUiThread(new Runnable() {
							public void run() {
								UiHelper.toast(FollowReadDetailsActivity.this,
										"该单元无数据");
								return;
							}
						});
					}

				} catch (Exception e) {
					Log.i("test", e.toString());
				}
			}
		});
	}

	/**
	 * 设置ViewPager的方法
	 */
	private void initVp() {
		adapter = new VpAdapter(getSupportFragmentManager());
		vp.setAdapter(adapter);
		vp.setOffscreenPageLimit(mFragments.size());
	}

	/**
	 * 设置监听的方法
	 * 
	 * @param v
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_back:
			// 返回
			finish();
			break;
		default:
			break;
		}
	}

	/**
	 * ViewPager的适配器
	 */
	class VpAdapter extends FragmentStatePagerAdapter {

		public VpAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int pos) {
			return mFragments.get(pos);
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

	}

	/**
	 * ViewPager的选中监听方法
	 * 
	 */
	@Override
	public void onPageScrollStateChanged(int pos) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int pos) {
		
		//当页面选中的时候通知AnswerFragment界面,如果播放按钮在进行播放,则进行清空处理
				sendBroadcast(new Intent("com.ycsj.goldmedalnewconcept.stopplay"));
		// 改变记录当前Vp的位置
		vpPos = pos;
		// 页面选中的时候需要改变顶部的进度条的进度,注意:这个pos是从0开始算的
		pb.setProgress(parsePb(pos + 1, mFragments.size()));
		tvPb.setText((pos + 1) + "/" + mFragments.size());
		int j = 0;
		for (int i = 0; i < currentItemList.size(); i++) {
			if(pos==currentItemList.get(i)){
				j = 1;
			}
		}
		if(j!=1){
			currentItemList.add(pos);
		}
		if(pos<currentItemList.size()-1){
			vp.setScrollble(true);
		}else{
			vp.setScrollble(false);
		}
		
	}

	/**
	 * 将两个Int相除取两位小数然后转化为Pb的百分比的方法
	 */
	private int parsePb(int a, int b) {

		DecimalFormat df = new DecimalFormat("0.00");

		return (int) (Float.valueOf(df.format((float) ((float) a / (float) b))) * 100);
	}

	
	@Override
	protected void onResume() {
		super.onResume();

		String gradeid = String.valueOf(lessonId).substring(0, 4);
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET,
				NetConstant.USERONLINE
						+ "InitInterfaceBegin.aspx?msg=1&type=9&account="
						+ SPUtils.getString(this, "account")
						+ "&gradeid=" + gradeid + "&lessonid=" + lessonId,
				callBackTime);

	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		String gradeid = String.valueOf(lessonId).substring(0, 4);
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET, NetConstant.USERONLINE
				+ "SaveInterfaceEnd.aspx?msg=1&rid=" + rid + "&account="
				+ SPUtils.getString(this, "account"),
				callBackTimefinish);
	}
	

	
	
	
	private RequestCallBack<String> callBackTime = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			Gson gson = new Gson();
			timeresq fromJson = gson.fromJson(json, timeresq.class);
			rid = fromJson.rid;
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			rid = "";
		}
	};
	
	private RequestCallBack<String> callBackTimefinish = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
		}

		@Override
		public void onFailure(HttpException error, String msg) {

		}
	};
	
	
	
	
	
	
	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

}
